var net = require('net');
var files = require('fs').createWriteStream('./message.txt');  //输出结果写入文件内
//var http =require("http");
var listenPort =8431;
var timeout =30000;
//net库建立的服务传给server变量
var server = net.createServer(function () {
    //response.end("客户端和服务端连接建立");//会打印2行
    console.log('连接建立"');
});

server.on("connection", function (socket) {
    const address = socket.address();
    console.log("连接的服务器的地址%j", address);
    socket.setEncoding('utf8');
    socket.setTimeout(timeout);

    socket.pause();
    //改写setTimeout,加入timeout事件
    socket.on('timeout', function () {
        socket.resume();
        console.log("客户端连接已经超时");
        socket.setTimeout(1000); //修改事件
        socket.pipe(files, {end: false});
    });

    //setTimeout(function(){
    //    socket.resume();
    //    socket.pipe(files,{end:false}); //写入到文件中，直到客户端关闭，引用到1个end事件
    //},10000);//10秒后写入数据

    //socket监听
    socket.on("data", function (data) {
        socket.pause();
        console.log('recv:',data.toString());
        console.log("recv的字节数 %d", socket.bytesRead);

        //setTimeout(function() {
        //socket.resume();
        //console.log(data.toString());
        // / },10000);//10秒后接收数据

    });
    setTimeout(function () {
        socket.on('end', function () {
            files.end("结束");
            socket.unpipe(file);
        }, 5000);
    });

    socket.on('close',function (data) {
       console.log("关闭"+socket.remoteAddress+''+remotePort); //关闭host+port
    });

});

//查看当前的连接数量
server.getConnections(function (error, count) {
    if (error) throw err;
    console.log("当前客户端连接有%j个", count)
    server.maxConnections = 2;
    console.log("当前服务器最大支出连接数%j", server.maxConnections);
});

server.listen(listenPort, "localhost", function () {
    var address = server.address();
    console.log("服务器被监听地址%j:", address,address.port) //地址和端口;
});

server.on('error', function (error) {

    if(error) console.log("server error:",error.message);
    else if (error.code !== "EADDRINUSE") {
        console.log("端口已经被占用", error.message);
    }
    else console.log("连接成功");
});
console.log("tcp服务被创建");